/*
 * Jenny Ruppen 09-730-391
 * Sebastien Goldberg 08-914-855
 * Henry Raymond 08-928-061
 * Stefan Mussato 09-752-270
 */
 
package ch.uzh.ifi.sopra.gruppe9.game;

import java.net.MalformedURLException;
import java.rmi.Naming;
import java.rmi.RemoteException;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;

/**
 * Static class for server functionality. Sets up Server and registers all remote objects with RMI.
 */
public final class Server {
	
	
	/**
	 * Unique instance of this class. Sets up registry and registers players.
	 */
	private static Server instance;
	
	
	/**
	 * Virtual game board
	 */
	private IGameBoard gameBoard;

	
	/**
	 * Constructor: set up Server and register all remote objects with RMI
	 */
	Server() throws RemoteException {
		//Create Registry for RMI
		try {
			LocateRegistry.createRegistry(Registry.REGISTRY_PORT);
		} catch (RemoteException ex) {
			System.out.println(ex.getMessage());
		}
		
		// Instantiate remote objects
		gameBoard = new GameBoard();
		
		// Bind remote objects in registry
		try {
			Naming.rebind("gameBoard", (IRmiGameBoard) gameBoard);
			Naming.rebind("baseElementMarket",      gameBoard.getBaseElementMarket());
			Naming.rebind("middleElementMarket",    gameBoard.getMiddleElementMarket());
			Naming.rebind("windowElementMarket",    gameBoard.getWindowElementMarket());
			Naming.rebind("roofElementMarket",      gameBoard.getRoofElementMarket());
			Naming.rebind("constructionAuthority",  gameBoard.getConstructionAuthority());
			Naming.rebind("palaceOfTheCaliph",      gameBoard.getPalaceOfTheCaliph());
			Naming.rebind("bank",                   gameBoard.getBank());
			Naming.rebind("houseOfSpies",           gameBoard.getHouseOfSpies());
			
		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (RemoteException e) {
			e.printStackTrace();
		}
	}

	
	/**
	 * Get unique instance of Server
	 */
	public static Server getInstance() throws RemoteException {
		//if(instance == null)
		//	instance = new Server();
		return instance;
	}
	
	public static void createInstance() throws RemoteException {		
			instance = new Server();
	}
	
	
	/**
	 * Binds player object to RMI registry
	 */
	public void registerPlayer(int index) {
		try {
			Naming.rebind("player" + index, (Player)gameBoard.getPlayer(index));
		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (RemoteException e) {
			e.printStackTrace();
		}
	}
}
